package com.easemob.helpdesk.adapter;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Toast;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.easemob.helpdesk.activity.MainActivity;
import com.easemob.helpdesk.activity.UserActivity;
import com.easemob.helpdesk.bean.User;
import com.easemob.helpdesk.bean.UserInfo;
import com.easemob.helpdesk.utils.CommonUtils;
import com.easemob.helpdesk.widget.chatrow.VideoViewHolder;
import com.housekeeperapp.BuildConfig;
import com.housekeeperapp.R;
import com.easemob.helpdesk.activity.ChatActivity;
import com.easemob.helpdesk.widget.chatrow.BaseViewHolder;
import com.easemob.helpdesk.widget.chatrow.FileViewHolder;
import com.easemob.helpdesk.widget.chatrow.ImageViewHolder;
import com.easemob.helpdesk.widget.chatrow.OrderOrTrackViewHolder;
import com.easemob.helpdesk.widget.chatrow.RecallViewHolder;
import com.easemob.helpdesk.widget.chatrow.RobotMenuViewHolder;
import com.easemob.helpdesk.widget.chatrow.TxtViewHolder;
import com.easemob.helpdesk.widget.chatrow.VoiceViewHolder;
import com.hyphenate.kefusdk.chat.HDClient;
import com.hyphenate.kefusdk.entity.HDMessage;
import com.hyphenate.kefusdk.manager.session.SessionManager;
import com.hyphenate.kefusdk.utils.MessageUtils;
import com.net.ApiService;
import com.net.BaseResponse;
import com.net.HKHttpUtils;
import com.net.HKResponseResultCallBack;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


/**
 * Created by lyuzhao on 2015/12/15.
 */
public class ChatAdapter extends RecyclerView.Adapter<BaseViewHolder> {

	private final String TAG = getClass().getSimpleName();

	private static final int MESSAGE_TYPE_SENT_TXT = 0;
	private static final int MESSAGE_TYPE_RECV_TXT = 1;
	private static final int MESSAGE_TYPE_SENT_IMAGE = 2;
	private static final int MESSAGE_TYPE_RECV_IMAGE = 3;
	private static final int MESSAGE_TYPE_RECV_ORDER = 4;
	private static final int MESSAGE_TYPE_RECV_TRACK = 5;
	private static final int MESSAGE_TYPE_SENT_VOICE = 6;
	private static final int MESSAGE_TYPE_RECV_VOICE = 7;
	private static final int MESSAGE_TYPE_SENT_FILE = 8;
	private static final int MESSAGE_TYPE_RECV_FILE = 9;
	private static final int MESSAGE_TYPE_SENT_ROBOTMENU = 10;
	private static final int MESSAGE_TYPE_RECV_ROBOTMENU = 11;
	private static final int MESSAGE_TYPE_RECALL_MESSAGE = 12;
	private static final int MESSAGE_TYPE_SENT_VIDEO = 13;
	private static final int MESSAGE_TYPE_RECV_VIDEO = 14;

	private LayoutInflater inflater;
	private Activity mActivity;
	public int mMinItemWidth;
	public int mMaxItemWidth;

	public View animView;
	public int animStatus = -1; // -1 not play; 0 sent play; 1 received play
	public boolean isAppChannel;
	private SessionManager sessionManager;
	private List<HDMessage> messageList;
	private RecyclerView mRecyclerView;

	private String userPhone;// 用户手机号
	private String username;

	public ChatAdapter(){

	}

	public ChatAdapter(Activity activity, SessionManager sessionManager, RecyclerView recyclerView, String username) {
		this.mActivity = activity;
		this.sessionManager = sessionManager;
		this.mRecyclerView = recyclerView;
		this.username = username;
		animStatus = -1;
		messageList = sessionManager.getAllMessages();
		inflater = LayoutInflater.from(mActivity);
		WindowManager wm = (WindowManager) activity.getSystemService(Context.WINDOW_SERVICE);
		DisplayMetrics displayMetrics = new DisplayMetrics();
		wm.getDefaultDisplay().getMetrics(displayMetrics);
		mMaxItemWidth = (int) (displayMetrics.widthPixels * 0.4f);
		mMinItemWidth = (int) (displayMetrics.widthPixels * 0.15f);
		if (activity instanceof ChatActivity) {
			isAppChannel = ((ChatActivity) activity).isAppChannel();
		}
	}


	/**
	 * 刷新页面
	 */
	public void refresh() {
		notifyDataSetChanged();
	}

	/**
	 * 刷新页面，选择最后一个
	 */
	public void refreshSelectLast() {
		if (messageList.size() > 0) {
			mRecyclerView.scrollToPosition(messageList.size() - 1);
		}
	}

	/**
	 * 刷新页面，选择Position
	 */
	public void refreshSeekTo(int position) {
		if (messageList.size() > 0) {
			mRecyclerView.scrollToPosition(position);
		}
	}

	public String getUserPhone(){
		return userPhone;
	}


	@Override
	public BaseViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
		View convertView = null;
		BaseViewHolder holder = null;
		switch (viewType) {
			case MESSAGE_TYPE_RECALL_MESSAGE:
				convertView = inflater.inflate(R.layout.row_recall_message, parent, false);
				holder = new RecallViewHolder(mActivity, this, convertView);
				break;
			case MESSAGE_TYPE_RECV_VOICE:
				convertView = inflater.inflate(R.layout.row_received_voice, parent, false);
				holder = new VoiceViewHolder(mActivity, this, convertView);
				break;
			case MESSAGE_TYPE_SENT_VOICE:
				convertView = inflater.inflate(R.layout.row_sent_voice, parent, false);
				holder = new VoiceViewHolder(mActivity, this, convertView);
				break;
			case MESSAGE_TYPE_RECV_ORDER:
				convertView = inflater.inflate(R.layout.row_received_order, parent, false);
				holder = new OrderOrTrackViewHolder(mActivity, this, convertView);
				break;
			case MESSAGE_TYPE_RECV_TRACK:
				convertView = inflater.inflate(R.layout.row_received_order, parent, false);
				holder = new OrderOrTrackViewHolder(mActivity, this, convertView);
				break;
			case MESSAGE_TYPE_SENT_IMAGE:
				convertView = inflater.inflate(R.layout.row_sent_picture, parent, false);
				holder = new ImageViewHolder(mActivity, this, convertView);
				break;
			case MESSAGE_TYPE_RECV_IMAGE:
				convertView = inflater.inflate(R.layout.row_received_picture, parent, false);
				holder = new ImageViewHolder(mActivity, this, convertView);
				break;
			case MESSAGE_TYPE_RECV_ROBOTMENU:
				convertView = inflater.inflate(R.layout.row_received_robotmenu_message, parent, false);
				holder = new RobotMenuViewHolder(mActivity, this, convertView);
				break;
			case MESSAGE_TYPE_SENT_ROBOTMENU:
				convertView = inflater.inflate(R.layout.row_sent_robotmenu_message, parent, false);
				holder = new RobotMenuViewHolder(mActivity, this, convertView);
				break;
			case MESSAGE_TYPE_RECV_TXT:
				convertView = inflater.inflate(R.layout.row_received_message, parent, false);
				holder = new TxtViewHolder(mActivity, this, convertView);
				break;
			case MESSAGE_TYPE_SENT_TXT:
				convertView = inflater.inflate(R.layout.row_sent_message, parent, false);
				holder = new TxtViewHolder(mActivity, this, convertView);
				break;
			case MESSAGE_TYPE_SENT_FILE:
				convertView = inflater.inflate(R.layout.row_sent_file, parent, false);
				holder = new FileViewHolder(mActivity, this, convertView);
				break;
			case MESSAGE_TYPE_RECV_FILE:
				convertView = inflater.inflate(R.layout.row_received_file, parent, false);
				holder = new FileViewHolder(mActivity, this, convertView);
				break;
			case MESSAGE_TYPE_SENT_VIDEO:
				convertView = inflater.inflate(R.layout.row_sent_video, parent, false);
				holder = new VideoViewHolder(mActivity, this, convertView);
				break;
			case MESSAGE_TYPE_RECV_VIDEO:
				convertView = inflater.inflate(R.layout.row_received_video, parent, false);
				holder = new VideoViewHolder(mActivity, this, convertView);
				break;
			default:break;
		}
		//noinspection ConstantConditions
		convertView.setLayoutParams(new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
		return holder;

	}

	private void getUserInfo(long id) {

		ApiService apiService = HKHttpUtils.getApiService();
		retrofit2.Call<BaseResponse<User>> call = apiService.getUserById(MainActivity.ticket,String.valueOf(id));
		call.enqueue(new HKResponseResultCallBack<User>() {
			@Override
			public void onSuccess(User user) {
				if(user != null){
					Intent intent = new Intent();
					intent.setClass(mActivity, UserActivity.class);
					intent.putExtra("id", user.getId());
					intent.putExtra("phone", user.getPhone());
					intent.putExtra("wxHeader", user.getWxHeader());
					intent.putExtra("homeAddress",  user.getHomeAddress());
					intent.putExtra("idcardNumber", user.getIdcardNumber());

					String wxname = user.getWxName();
					try {
						if(!CommonUtils.isBlank(wxname)) {
							String decodeStr = URLDecoder.decode(wxname, "utf-8");
							intent.putExtra("wxname", decodeStr);
						}else{
							intent.putExtra("wxname", "");
						}

					} catch (UnsupportedEncodingException e) {
						e.printStackTrace();
						intent.putExtra("wxname", wxname);
					}

					String name = user.getName();

					if(!CommonUtils.isBlank(name)){
						intent.putExtra("name", name);
					}else{
						intent.putExtra("name", "");
					}

					intent.putExtra("originType", "rest");
					intent.putExtra("techChannelName", "");
//					intent.putExtra("visitorid", visitorId);
					intent.putExtra("chatGroupId", 0L);
					mActivity.startActivity(intent);

				}
			}

			@Override
			public void onGetDataFailed(int cd, String msg) {
				Toast.makeText(mActivity, msg, Toast.LENGTH_SHORT).show();
			}

			@Override
			public void onFailed(retrofit2.Call call, Throwable t) {
				Toast.makeText(mActivity, "请求失败", Toast.LENGTH_SHORT).show();
			}
		});
//		OkHttpClient okHttpClient = new OkHttpClient();
//
//		RequestBody body = new FormBody.Builder()
//				.add("uid", String.valueOf(id))
//				.build();
//
//		Request request = new Request.Builder()
//				.url(BuildConfig.API_URL + "account/findUserById")
//				.post(body)
//				.build();
//
//		Call call = okHttpClient.newCall(request);
//
//		call.enqueue(new Callback() {
//			@Override
//			public void onFailure(Call call, IOException e) {
//				e.printStackTrace();
//				Toast.makeText(mActivity, "请求失败", Toast.LENGTH_SHORT).show();
//			}
//
//			@Override
//			public void onResponse(Call call, Response response) throws IOException {
//
//				final String res = response.body().string();
//				final UserInfo result = CommonUtils.parseJsonWithGson(res, UserInfo.class);
//				mActivity.runOnUiThread(new Runnable() {
//					@Override
//					public void run() {
//						if(result.getData() != null){
//							Intent intent = new Intent();
//							intent.setClass(mActivity, UserActivity.class);
//							intent.putExtra("id", result.getData().getId());
//							intent.putExtra("phone", result.getData().getPhone());
//							intent.putExtra("wxHeader", result.getData().getWxHeader());
//							intent.putExtra("homeAddress",  result.getData().getHomeAddress());
//							intent.putExtra("idcardNumber", result.getData().getIdcardNumber());
//
//							String wxname = result.getData().getWxName();
//							try {
//								if(!CommonUtils.isBlank(wxname)) {
//									String decodeStr = URLDecoder.decode(wxname, "utf-8");
//									intent.putExtra("wxname", decodeStr);
//								}else{
//									intent.putExtra("wxname", "");
//								}
//
//							} catch (UnsupportedEncodingException e) {
//								e.printStackTrace();
//								intent.putExtra("wxname", wxname);
//							}
//
//							String name = result.getData().getName();
//
//							if(!CommonUtils.isBlank(name)){
//								intent.putExtra("name", name);
//							}else{
//								intent.putExtra("name", "");
//							}
//
//							intent.putExtra("originType", "rest");
//							intent.putExtra("techChannelName", "");
////					intent.putExtra("visitorid", visitorId);
//							intent.putExtra("chatGroupId", 0L);
//							mActivity.startActivity(intent);
//
//						}
//					}
//				});
//
//			}
//		});

	}


	@Override
	public void onBindViewHolder(BaseViewHolder holder, final int position) {
		if (position > messageList.size()) {
			return;
		}
		final HDMessage message = messageList.get(position);
		if (message.direct() == HDMessage.Direct.RECEIVE) {
			if (sessionManager.isAgentChat()) {
				holder.ivAvatar.setImageResource(R.drawable.default_agent_avatar);
			} else {
				//获取用户头像
				JSONObject extJson = message.getExtJson();
				if(extJson != null && extJson.has("weichat")) {
					try {
						JSONObject jsonWeichat = extJson.getJSONObject("weichat");
						if(jsonWeichat != null) {
							JSONObject visitorJson = jsonWeichat.getJSONObject("visitor");
							if(visitorJson != null){
								String url = visitorJson.getString("description");
								Glide.with(mActivity).load(url)
										.diskCacheStrategy(DiskCacheStrategy.RESOURCE).placeholder(R.drawable.default_customer_avatar).error(R.drawable.default_customer_avatar)
										.into(holder.ivAvatar);

							}
						}

					} catch (JSONException var3) {
						var3.printStackTrace();
					}

				}

				//点击头像到详情页面
				holder.ivAvatar.setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						if(!CommonUtils.isBlank(username) && username.contains("#")){
							String uid = username.split("#")[0];
							getUserInfo(Long.parseLong(uid));
						}
					}
				});
			}

		} else {
			if (message.getFromUser().isSelf()) {
				String avatarUrl = HDClient.getInstance().getCurrentUser().getAvatar();
				if (TextUtils.isEmpty(avatarUrl)) {
					holder.ivAvatar.setImageResource(R.drawable.default_agent_avatar);
				} else {
					if (!avatarUrl.startsWith("http")) {
						avatarUrl = "http:" + avatarUrl;
					}

					Glide.with(mActivity).load(avatarUrl)
							.diskCacheStrategy(DiskCacheStrategy.RESOURCE).placeholder(R.drawable.default_agent_avatar).error(R.drawable.default_agent_avatar)
							.into(holder.ivAvatar);
				}

			} else {
				if (holder.ivAvatar != null)
					holder.ivAvatar.setImageResource(R.drawable.default_agent_avatar);
			}
		}
		holder.handleMessage(message, position);
	}

	public HDMessage getItem(int position) {
		if (sessionManager.getAllMessages() != null && position < sessionManager.getAllMessages().size()) {
			return sessionManager.getAllMessages().get(position);
		}
		return null;
	}


	@Override
	public int getItemCount() {
		return messageList.size();
	}

	@Override
	public int getItemViewType(int position) {
		HDMessage message = messageList.get(position);
		if (message == null) {
			return -1;
		}
		if (MessageUtils.isRecallMessage(message)) {
			return MESSAGE_TYPE_RECALL_MESSAGE;
		}

		boolean isSend = message.direct() == HDMessage.Direct.SEND;
		if (message.getType() == HDMessage.Type.VOICE) {
			if (isSend) {
				return MESSAGE_TYPE_SENT_VOICE;
			} else {
				return MESSAGE_TYPE_RECV_VOICE;
			}
		} else if (message.getType() == HDMessage.Type.FILE) {
			if (isSend) {
				return MESSAGE_TYPE_SENT_FILE;
			} else {
				return MESSAGE_TYPE_RECV_FILE;
			}
		} else if (message.getType() == HDMessage.Type.IMAGE) {
			if (isSend) {
				return MESSAGE_TYPE_SENT_IMAGE;
			} else {
				return MESSAGE_TYPE_RECV_IMAGE;
			}
		} else if (message.getType() == HDMessage.Type.VIDEO) {
			if (isSend) {
				return MESSAGE_TYPE_SENT_VIDEO;
			} else {
				return MESSAGE_TYPE_RECV_VIDEO;
			}
		} else if (message.getType() == HDMessage.Type.TXT) {
			if (MessageUtils.isRobotMenuMessage(message)) {
				if (isSend) {
					return MESSAGE_TYPE_SENT_ROBOTMENU;
				} else {
					return MESSAGE_TYPE_RECV_ROBOTMENU;
				}
			} else if (MessageUtils.isOrderOrTrackMessage(message)) {
				if (isSend) {
					return MESSAGE_TYPE_SENT_TXT;
				} else {
					return MESSAGE_TYPE_RECV_ORDER;
				}
			} else {
				if (isSend) {
					return MESSAGE_TYPE_SENT_TXT;
				} else {
					return MESSAGE_TYPE_RECV_TXT;
				}
			}
		}
		return super.getItemViewType(position);
	}
}
